<template>
  <div class="game-list">
    <div class="header">
      <el-button type="primary" @click="handleAdd">新增游戏</el-button>
    </div>

    <!-- 游戏列表表格 -->
    <el-table 
      :data="gameList" 
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="ID" label="ID" width="80" />
      <el-table-column prop="game_name" label="游戏名称" min-width="120" show-overflow-tooltip />
      <el-table-column prop="game_introduce" label="游戏简介" min-width="180" show-overflow-tooltip />
      <el-table-column prop="game_developer" label="开发者" min-width="120" show-overflow-tooltip />
      <el-table-column prop="game_class" label="游戏分类" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.game_class === 1 ? 'primary' : 'success'">
            {{ gameClassMap[scope.row.game_class] || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="game_icon" label="游戏图标" width="100">
        <template #default="scope">
          <el-image 
            v-if="scope.row.game_icon"
            :src="getFullImageUrl(scope.row.game_icon)"
            style="width: 50px; height: 50px"
            :preview-src-list="[getFullImageUrl(scope.row.game_icon)]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="game_banner" label="游戏横幅" width="150">
        <template #default="scope">
          <div class="banner-list">
            <el-image 
              v-for="(banner, index) in getBannerImages(scope.row.game_banner)"
              :key="index"
              :src="getFullImageUrl(banner.img)"
              style="width: 100px; height: 50px; margin-right: 5px"
              :preview-src-list="getBannerImages(scope.row.game_banner).map(b => getFullImageUrl(b.img))"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="game_percentage" label="分成比例" width="100">
        <template #default="scope">
          <span>{{ scope.row.game_percentage }}%</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="success" size="small" @click="handleGameTerm(scope.row)">游戏项</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 30, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 游戏表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="gameForm" :rules="rules" ref="gameFormRef" label-width="120px">
        <el-form-item label="游戏名称" prop="game_name">
          <el-input v-model="gameForm.game_name" />
        </el-form-item>
        <el-form-item label="游戏简介" prop="game_introduce">
          <el-input v-model="gameForm.game_introduce" type="textarea" />
        </el-form-item>
        <el-form-item label="开播文档" prop="game_start_document">
          <el-input v-model="gameForm.game_start_document" type="textarea" />
        </el-form-item>
        <el-form-item label="开发者" prop="game_developer">
          <el-input v-model="gameForm.game_developer" />
        </el-form-item>
        <el-form-item label="游戏分类" prop="game_class">
          <el-select v-model="gameForm.game_class">
            <el-option :value="1" label="对战类" />
            <el-option :value="2" label="比赛类" />
            <el-option :value="3" label="竞技类" />
            <el-option :value="4" label="攻防类" />
            <el-option :value="5" label="休闲类" />
            <el-option :value="6" label="合作类" />
          </el-select>
        </el-form-item>
        <el-form-item label="游戏图标" prop="game_icon">
          <div class="game-icon-container">
            <el-upload
              class="upload-demo"
              drag
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="(res) => handleUploadSuccess(res, 'game_icon')"
              :before-upload="beforeUpload"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽文件到此处或者 <em>点击上传</em></div>
            </el-upload>
            <div class="icon-preview" v-if="gameForm.game_icon">
              <img :src="getFullImageUrl(gameForm.game_icon)" alt="游戏图标" class="game-icon-image" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="游戏横幅" prop="game_banner">
          <div class="game-banner-container">
            <el-upload
              class="upload-demo"
              drag
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="(res) => handleUploadSuccess(res, 'game_banner')"
              :before-upload="beforeUpload"
              multiple
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽文件到此处或者 <em>点击上传</em></div>
              <div class="el-upload__tip">可以上传多个横幅图片</div>
            </el-upload>
            <div class="banner-preview-list">
              <div 
                v-for="(banner, index) in getBannerImages(gameForm.game_banner)" 
                :key="index"
                class="banner-preview-item"
              >
                <img :src="getFullImageUrl(banner.img)" alt="游戏横幅" class="game-banner-image" />
                <div class="banner-preview-actions">
                  <el-button 
                    type="danger" 
                    size="small" 
                    circle
                    @click="removeBanner(index)"
                  >
                    <el-icon><delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="分成比例" prop="game_percentage">
          <el-input-number v-model="gameForm.game_percentage" :min="0" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 游戏项对话框 -->
    <el-dialog
      title="游戏项管理"
      v-model="termDialogVisible"
      width="800px"
    >
      <div class="term-header">
        <el-button type="primary" @click="handleAddTerm">新增游戏项</el-button>
      </div>
      <el-table :data="gameTermList" style="width: 100%; margin-top: 20px">
        <el-table-column prop="game_version" label="版本号" />
        <el-table-column prop="game_key" label="文件名" />
        <el-table-column prop="game_md5" label="MD5" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDeleteTerm(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 游戏项表单 -->
      <el-dialog
        title="新增游戏项"
        v-model="termFormVisible"
        width="500px"
        append-to-body
      >
        <el-form :model="termForm" :rules="termRules" ref="termFormRef" label-width="100px">
          <el-form-item label="版本号" prop="game_version">
            <el-input v-model="termForm.game_version" />
          </el-form-item>
          <el-form-item label="文件名" prop="game_key">
            <el-input v-model="termForm.game_key" />
          </el-form-item>
          <el-form-item label="MD5" prop="game_md5">
            <el-input v-model="termForm.game_md5" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="termFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitTermForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { UploadFilled, Delete } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import type { ApiResponse } from '@/utils/request'
import request from '@/utils/request'
import {
  createGame,
  updateGame,
  getGameList,
  deleteGame,
  createGameTerm,
  getGameTermList,
  deleteGameTerm
} from '@/api/game'

// 定义游戏和游戏项的接口类型
interface Game {
  ID: number
  game_name: string
  game_introduce: string
  game_start_document: string
  game_developer: string
  game_class: number
  game_icon: string
  game_banner: string
  game_percentage: number
  sys_user_id: number
  status: number
  CreatedAt: string
  UpdatedAt: string
}

interface GameTerm {
  ID: number
  game_version: string
  game_key: string
  game_md5: string
  sys_game_id: number
}

// 游戏分类映射
const gameClassMap = {
  1: '对战类',
  2: '比赛类',
  3: '竞技类',
  4: '攻防类',
  5: '休闲类',
  6: '合作类'
}

// 游戏列表数据
const gameList = ref<Game[]>([])
const gameTermList = ref<GameTerm[]>([])

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const termDialogVisible = ref(false)
const termFormVisible = ref(false)

// 表单数据
const gameFormRef = ref()
const gameForm = ref({
  game_name: '',
  game_introduce: '',
  game_start_document: '',
  game_developer: '',
  game_class: 1,
  game_icon: '',
  game_banner: '',
  game_percentage: 10,
  sys_user_id: 1,
  ID: undefined
})

// 游戏项表单数据
const termFormRef = ref()
const termForm = ref<{
  game_version: string
  game_key: string
  game_md5: string
  sys_game_id: number | null
}>({
  game_version: '',
  game_key: '',
  game_md5: '',
  sys_game_id: null
})

// 表单验证规则
const rules = {
  game_name: [{ required: true, message: '请输入游戏名称', trigger: 'blur' }],
  game_introduce: [{ required: true, message: '请输入游戏简介', trigger: 'blur' }],
  game_start_document: [{ required: true, message: '请输入开播文档', trigger: 'blur' }],
  game_developer: [{ required: true, message: '请输入开发者', trigger: 'blur' }],
  game_class: [{ required: true, message: '请选择游戏分类', trigger: 'change' }],
  game_icon: [{ required: true, message: '请上传游戏图标', trigger: 'change' }],
  game_banner: [{ required: true, message: '请上传游戏横幅', trigger: 'change' }],
  game_percentage: [{ required: true, message: '请输入分成比例', trigger: 'blur' }]
}

const termRules = {
  game_version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  game_key: [{ required: true, message: '请输入文件名', trigger: 'blur' }],
  game_md5: [{ required: true, message: '请输入MD5', trigger: 'blur' }]
}

// 加载状态
const loading = ref(false)

// 分页配置
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

// 服务器基础URL
const BASE_URL = 'http://211.154.24.179'

// 计算完整的图片URL
const getFullImageUrl = (url: string) => {
  if (!url) return ''
  if (url.startsWith('http')) {
    return url
  }
  return `${BASE_URL}${url}`
}

// 从本地存储获取 token
const token = localStorage.getItem('vue_admin_template_token')

// 上传文件的接口地址
const uploadUrl = 'http://211.154.24.179/api/qiniu/UploadFile'

// 上传文件的请求头
const uploadHeaders = {
  Authorization: `${token}`
}

// 获取横幅图片数组
const getBannerImages = (bannerStr: string) => {
  if (!bannerStr) return []
  try {
    const bannerArray = JSON.parse(bannerStr)
    if (Array.isArray(bannerArray)) {
      return bannerArray
    }
    return []
  } catch (error) {
    console.error('解析横幅数据失败:', error)
    return []
  }
}

// 移除横幅图片
const removeBanner = (index: number) => {
  try {
    const banners = getBannerImages(gameForm.value.game_banner)
    banners.splice(index, 1)
    gameForm.value.game_banner = JSON.stringify(banners)
  } catch (error) {
    console.error('移除横幅失败:', error)
    ElMessage.error('移除横幅失败')
  }
}

// 文件上传成功后的回调
const handleUploadSuccess = (response: any, field: 'game_icon' | 'game_banner') => {
  if (response.success) {
    if (field === 'game_banner') {
      // 获取现有的横幅数组
      const currentBanners = getBannerImages(gameForm.value.game_banner)
      // 添加新的横幅
      currentBanners.push({ img: response.data })
      // 更新表单数据
      gameForm.value[field] = JSON.stringify(currentBanners)
    } else {
      gameForm.value[field] = response.data
    }
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败')
  }
}

// 文件上传前的钩子
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 获取游戏列表
const fetchGameList = async () => {
  loading.value = true
  try {
    const res = await getGameList(pagination.value.page, pagination.value.size)
    console.log('API响应数据:', res)
    
    if (res && res.data) {
      // 假设返回数据格式为 { list: [], total: number }
      if (typeof res.data === 'object' && 'list' in res.data) {
        gameList.value = res.data.list || []
        pagination.value.total = res.data.total || 0
      } else {
        // 如果返回的直接是数组
        const data = Array.isArray(res.data) ? res.data : [res.data]
        gameList.value = data
        pagination.value.total = data.length
      }
      console.log('处理后的游戏列表数据:', gameList.value)
    } else {
      console.warn('API返回的数据格式不正确:', res)
      gameList.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取游戏列表失败:', error)
    ElMessage.error('获取游戏列表失败')
    gameList.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 获取游戏项列表
const fetchGameTermList = async (gameId: number) => {
  try {
    const res = await getGameTermList()
    console.log('游戏项API响应数据:', res)
    
    if (res && res.data) {
      const data = Array.isArray(res.data) ? res.data : [res.data]
      gameTermList.value = data.filter((item: GameTerm) => item.sys_game_id === gameId)
      console.log('处理后的游戏项列表数据:', gameTermList.value)
    } else {
      console.warn('游戏项API返回的数据格式不正确:', res)
      gameTermList.value = []
    }
  } catch (error) {
    console.error('获取游戏项列表失败:', error)
    ElMessage.error('获取游戏项列表失败')
    gameTermList.value = []
  }
}

// 新增游戏
const handleAdd = () => {
  dialogTitle.value = '新增游戏'
  gameForm.value = {
    game_name: '',
    game_introduce: '',
    game_start_document: '',
    game_developer: '',
    game_class: 1,
    game_icon: '',
    game_banner: '',
    game_percentage: 10,
    sys_user_id: 1,
    ID: undefined
  }
  dialogVisible.value = true
}

// 编辑游戏
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑游戏'
  gameForm.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!gameFormRef.value) return
  
  await gameFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (gameForm.value.ID) {
          await updateGame(gameForm.value)
          ElMessage.success('更新成功')
        } else {
          await createGame(gameForm.value)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        fetchGameList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除游戏
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该游戏吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteGame(row.ID)
      ElMessage.success('删除成功')
      fetchGameList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 游戏项管理
const handleGameTerm = (row: Game) => {
  termForm.value.sys_game_id = row.ID
  termDialogVisible.value = true
  fetchGameTermList(row.ID)
}

// 新增游戏项
const handleAddTerm = () => {
  if (!termForm.value.sys_game_id) {
    ElMessage.error('游戏ID不能为空')
    return
  }
  
  termForm.value = {
    game_version: '',
    game_key: '',
    game_md5: '',
    sys_game_id: termForm.value.sys_game_id
  }
  termFormVisible.value = true
}

// 提交游戏项表单
const submitTermForm = async () => {
  if (!termFormRef.value || !termForm.value.sys_game_id) return
  
  await termFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await createGameTerm(termForm.value)
        ElMessage.success('创建成功')
        termFormVisible.value = false
        fetchGameTermList(termForm.value.sys_game_id!)
      } catch (error) {
        console.error('创建失败:', error)
        ElMessage.error('创建失败')
      }
    }
  })
}

// 删除游戏项
const handleDeleteTerm = (row: any) => {
  ElMessageBox.confirm('确认删除该游戏项吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteGameTerm(row.ID)
      ElMessage.success('删除成功')
      fetchGameTermList(row.sys_game_id)
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 处理每页显示数量变化
const handleSizeChange = (val: number) => {
  pagination.value.size = val
  pagination.value.page = 1 // 重置到第一页
  fetchGameList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchGameList()
}

onMounted(() => {
  fetchGameList()
})
</script>

<style scoped>
.game-list {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.term-header {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
}

.upload-demo {
  width: 100%;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 200px;
}

.game-icon-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.icon-preview {
  width: 100px;
  height: 100px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.game-icon-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.game-banner-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.banner-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.banner-preview-item {
  position: relative;
  width: 200px;
  height: 100px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.banner-preview-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: none;
}

.banner-preview-item:hover .banner-preview-actions {
  display: block;
}

.game-banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>